<template>
  <el-dialog
    v-el-drag-dialog
    :title="title"
    :visible.sync="visible"
    append-to-body
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" label-width="90px" class="form" :model="temp" :rules="rules">
      <el-form-item label="计划编号:" prop="name">
        <el-input v-model="temp.planCode" :maxlength="20" placeholder="请输入" :disabled="type !== 'add'">
          <el-button
            v-if="type === 'add'"
            slot="append"
            class="append-search"
            @click="getCode"
          >获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="计划名称:" prop="planName">
        <el-input
          v-model="temp.planName"
          :disabled="type === 'detail'"
          :maxlength="20"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="配送时间:"
        prop="sendTime"
      >
        <el-input-number
          v-model="temp.sendTime"
          :disabled="type === 'detail'"
          controls-position="right"
          :min="0"
          :max="23"
          :precision="0"
        />
      </el-form-item>
      <el-form-item label="配送周期:" :table-form-merge="2" class="merge-item" prop="sendSchedule">
        <el-select
          ref="selectDate"
          v-model="temp.sendSchedule"
          :disabled="type === 'detail'"
          multiple
          popper-append-to-body
          placeholder="请选择"
          @visible-change="selectDate"
        >
          <!-- <el-option>
            <el-tabs slot="prefix" v-model="activeName" type="card">
              <el-tab-pane label="配送客户审核" name="second">配送客户审核</el-tab-pane>
              <el-tab-pane label="配送客户查询" name="third">配送客户查询</el-tab-pane>
            </el-tabs>
          </el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item prop="remark" label="备注:" class="block">
        <el-input
          v-model="temp.remark"
          :disabled="type === 'detail'"
          type="textarea"
          :rows="2"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="配送商品" name="first">
        <el-form
          v-if="type !== 'detail'"
          ref="form"
          label-width="80px"
          class="goodsForm"
          :model="goods"
        >
          <el-form-item label="商品分类:" prop="address">
            <el-tree-select
              v-model="shop.gtId"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                props: {
                  value: 'gtId',
                  label: 'gtName',
                  disabled: 'disabled',
                },
                data: goodsTreeData,
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item label="商品名称:" prop="address">
            <el-select v-model="shop.goodsId" clearable>
              <el-option
                v-for="(l, i) in goodsTypesDetailList"
                :key="i"
                :value="l.goodsId"
                :label="l.goodsName"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 20%;" class="btn" label-width="20px">
            <el-button type="primary" @click="addGoods">添加</el-button>
          </el-form-item>
        </el-form>
        <lb-table
          ref="lbTable"
          class="tableOrder"
          highlight-current-row
          max-height="400"
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          :pagination="false"
          :total="tableData.total"
        />
      </el-tab-pane>
      <el-tab-pane label="配送客户" name="second">
        <peiSongUser ref="peisongUser" :type="type" />
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button
        v-if="type !== 'detail'"
        :loading="$loadingPlugin.add || $loadingPlugin.edit"
        type="primary"
        @click="success"
      >
        保存
      </el-button>
    </div>
    <period ref="period" @getPeriod="getPeriod" />
  </el-dialog>
</template>

<script>
  import {
    goodsTypeQueryList,
    orderSendPlanDetail,
    getCodeNum,
    goodsTypeDetail,
    orderSendPlanAdd,
    orderSendPlanUpdate
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  export default {
    name: 'add',
    components: {
      peiSongUser: require('./peisongUser').default,
      period: require('./period.vue').default
    },
    data() {
      return {
        visible: false,
        type: 'add',
        title: '新增计划',
        activeName: 'first',
        goodsTypesDetailList: [],
        goodsTreeData: [],
        shop: {
          goodsId: null,
          gtId: null
        },
        treeData: [],
        tableData: {
          column: [
            { type: 'index', align: 'center' },
            { label: '商品类型', prop: 'gtName', width: 200 },
            { label: '商品编号', prop: 'goodsCode', width: 120 },
            { label: '商品名称', prop: 'goodsName', width: '', align: 'center' },
            { label: '单位', prop: 'unitName', width: 120, align: 'center' },
            {
              label: '配送数量',
              prop: 'sendCount',
              width: 120,
              align: 'left',
              render: (h, scope) => (
              <el-input-number
                max={9999}
                min={1}
                controls={false}
                value={scope.row[scope.column.property]}
                disabled={this.type === 'detail'}
                style='width: 90px;'
                onInput={(val) => {
                  scope.row[scope.column.property] = val
                }}
              ></el-input-number>
            )
            },
            {
              label: '操作',
              prop: '',
              width: 60,
              align: 'left',
              fixed: 'right',
              render: (h, { row, $index }) =>
                this.type !== 'detail' && (
                <el-link
                  underline={false}
                  type='danger'
                  onClick={() => {
                    this.del($index)
                  }}
                >
                  {' '}
                  删除
                </el-link>
              )
            }
          ],
          data: []
        },
        goods: {},
        temp: {
          planCode: '', // 计划编号
          planName: '', // 计划名称
          sendTime: undefined, // 配送时间
          sendType: 1, // 配送周期类型 月 星期
          sendSchedule: [], // 配送周期
          remark: '' // 备注
        },
        sendType3: null, // 当选择sendType为3时的天数
        oldPlanCode: null,
        rules: {
          planName: [{ required: true, message: '请输入计划名称', trigger: 'change' }],
          sendTime: [{ required: true, message: '请输入配送时间', trigger: 'change' }],
          sendSchedule: [{ required: true, message: '请选择配送周期', trigger: 'change' }]
        }
      }
    },
    mounted() {
      this.getGoodsTreeData()
    // this.getTreeData()
    },
    methods: {
      // 获取计划编号
      async getCode() {
        const res = await getCodeNum({ type: 19 })
        this.temp.planCode = res.data
      },
      // // 获取树图数据
      // async getTreeData() {
      //   const res = await goodsTypeQueryList({})
      //   const data = res.data.map(item => ({
      //     label: item.gtName,
      //     ...item
      //   }))
      //   this.treeData = getTreeData(data, null, 'gtId')
      // },
      selectDate(val) {
        if (val) {
          this.$refs.period.open()

          this.$refs.selectDate.visible = false
        }
      },
      addGoods() {
        // console.log(this.goods.goodsType)
        // this.tableData.data.push({ ...this.goods })
        const goods = this.goodsTypesDetailList.find(
          (l) => l.goodsId === this.shop.goodsId
        )
        if (!goods || !goods.goodsId) {
          this.$message.error('请选择商品')
          return
        }
        var rows = this.tableData.data
        if (rows.length > 0) {
          var index = rows.findIndex(function(item) {
            return item.goodsId === goods.goodsId
          })
          if (index > -1) {
            this.$message.error('该商品已存在')
            return
          }
        }
        var row = {
          // rowId: ++ord_sendPlan_add_win.current.rowId,
          gtId: goods.gTypeId,
          gtName: goods.gtName,
          goodsId: goods.goodsId,
          goodsCode: goods.goodsCode,
          goodsName: goods.goodsName,
          unitId: goods.unitId,
          unitName: goods.unitName,
          pricingMode: goods.pricingMode,
          sendCount: 1
        }
        this.tableData.data.push(row)
      },
      // 选择数量
      changeNum(row, index, event) {
      // console.log(row)
      // // console.log(index)
      // const value = event.target.value.replace(/[^\d]/g,'')
      // row.gcount = value
      },
      del(index) {
        this.tableData.data.splice(index, 1)
      },
      async open(temp, type) {
        return new Promise(async(resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.type = 'edit'
            this.title = '编辑计划'
            if (type) {
              this.type = 'detail'
              this.title = '计划详情'
            }
            this.oldPlanCode = temp.planCode
            const res = await orderSendPlanDetail({ planCode: temp.planCode }) // 主要数据
            this.temp = { ...res.data }
            this.temp.sendTime = new Date(res.data.sendTime).getHours()
            this.tableData.data = res.data.goodsList
            this.$refs.peisongUser.tableData.data = res.data.csmList
            this.$refs.peisongUser.submitTableData = JSON.parse(JSON.stringify(res.data.csmList))
            const sendType = res.data.sendType
            this.$refs.period.sendType = String(sendType)
            let schedule = res.data.sendSchedule
            if (schedule) {
              schedule = schedule.replaceAll('周', '')
            }
            if (sendType * 1 === 3) {
              this.$refs.period.sendSchedule = schedule
              this.sendType3 = schedule
            } else if (sendType * 1 === 2) {
              this.$refs.period.sendScheduleList = schedule.split(',')
            } else if (sendType * 1 === 1) {
              this.$refs.period.sendScheduleList = schedule.split(',')
            }
            this.$refs.period.success()
          } else {
            this.type = 'add'
            this.title = '新增计划'
          }
        })
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const { planCode, planName, sendTime, remark, sendType } = this.temp

          var goodsList = this.tableData.data
          var csmList = this.$refs.peisongUser.submitTableData
          if (goodsList.length === 0) {
            this.$message.error('请添加配送商品')
            return
          }
          var reg = /^\+?[1-9]\d*$/
          for (var i = 0; i < goodsList.length; i++) {
            if (!goodsList[i].sendCount) {
              this.$message.error('请输入配送数量')
              return
            } else {
              if (!reg.test(goodsList[i].sendCount)) {
                this.$message.error('配送数量错误 请核对后在操作')
                return
              }
            }
          }
          if (csmList.length === 0) {
            this.$message.error('请添加配送客户')
            return
          }
          const params = {
            planCode: planCode,
            oldPlanCode: this.oldPlanCode,
            planName: planName,
            sendTime: new Date('2000-01-01 00:00:00').setHours(sendTime * 1),
            sendType: sendType,
            sendSchedule: null,
            remark: remark,
            goodsList: goodsList,
            csmList: csmList
          }
          if (sendType * 1 === 3) {
            params['sendSchedule'] = this.sendType3
          } else if (sendType * 1 === 2) {
            params['sendSchedule'] = this.temp.sendSchedule.join(',')
          } else if (sendType * 1 === 1) {
            var list = this.temp.sendSchedule.map((l) => {
              return l.substr(0, l.length - 1)
            })
            params['sendSchedule'] = list.join(',')
          }
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await orderSendPlanAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await orderSendPlanUpdate(params)
        this.resolve(this.temp)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      getPeriod(sendSchedule, sendType) {
        console.log(sendSchedule)
        this.temp.sendType = sendType
        if (!sendSchedule) return
        if (sendType === '1') {
          this.temp.sendSchedule = sendSchedule.map((l) => {
            return l + '号'
          })
        } else if (sendType === '2') {
          this.temp.sendSchedule = sendSchedule.map((l) => {
            if (l === 7) {
              return '周日'
            }
            return '周' + l
            // return l
          })
        } else if (sendType === '3') {
          this.sendType3 = sendSchedule
          this.temp.sendSchedule = ['每' + sendSchedule + '天']
        }
      },
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map((item) => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data, 'parentId', 'gtId')
      },
      // 选择商品分类
      async selectTreeChange(value) {
        this.shop.goodsId = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
        // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      reset() {
        this.temp = {
          planCode: '', // 计划编号
          planName: '', // 计划名称
          sendTime: undefined, // 配送时间
          sendType: 1, // 配送周期类型 月 星期
          sendSchedule: [], // 配送周期
          remark: '' // 备注
        }
        this.shop = {
          goodsId: null,
          gtId: null
        }
        this.activeName = 'first'
        this.tableData.data = []
        this.$refs['peisongUser'].tableData.data = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.goodsForm {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 40%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
